package com.flydust.apipulse.service;

import com.flydust.apipulse.entity.Directory;
import com.flydust.apipulse.entity.Endpoint;
import com.flydust.apipulse.repository.EndpointRepository;
import com.flydust.apipulse.repository.DirectoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class EndpointService {

    @Autowired
    private EndpointRepository endpointRepository;
    
    @Autowired
    private DirectoryRepository directoryRepository;

    public List<Endpoint> findByProjectId(Long projectId) {
        return endpointRepository.findByProjectId(projectId);
    }

    public List<Endpoint> findByProjectIdAndDirectoryId(Long projectId, Long directoryId) {
        return endpointRepository.findByProjectIdAndDirectoryId(projectId, directoryId);
    }

    public List<Endpoint> findByProjectIdAndNullDirectoryId(Long projectId) {
        return endpointRepository.findByProjectIdAndDirectoryIdIsNull(projectId);
    }

    public Optional<Endpoint> findById(Long id) {
        return endpointRepository.findById(id);
    }

    public Endpoint save(Endpoint endpoint) {
        // 如果没有设置目录ID，则设置为默认目录
        if (endpoint.getDirectoryId() == null) {
            // 查找项目中的默认目录
            List<Directory> directories = directoryRepository.findByProjectId(endpoint.getProjectId());
            Directory defaultDirectory = null;
            
            for (Directory dir : directories) {
                if ("默认".equals(dir.getName())) {
                    defaultDirectory = dir;
                    break;
                }
            }
            
            // 如果找到了默认目录，则使用它
            if (defaultDirectory != null) {
                endpoint.setDirectoryId(defaultDirectory.getId());
            }
        }
        
        return endpointRepository.save(endpoint);
    }

    public void deleteById(Long id) {
        endpointRepository.deleteById(id);
    }

    public List<Endpoint> findAll() {
        return endpointRepository.findAll();
    }
}